import axios from "axios";
import { Message } from "element-ui";
import router from "../router";
import qs from 'qs'
axios.defaults.baseURL = 'http://127.0.0.1:9000'
axios.defaults.timeout = 10000
axios.defaults.withCredentials = true

//配置拦截器带token
axios.interceptors.request.use(config=>{
    let userInfo = localStorage.getItem('userInfo')
    // console.log(token)

    userInfo = JSON.parse(userInfo)
    console.log(userInfo)
    if (userInfo && userInfo!== ""){
        config.headers.Bearer = userInfo.token
    }
    return config
},error => {
    return Promise.reject(error)
});
//响应拦截
axios.interceptors.response.use(function (response) {
    // 在接收响应做些什么，例如跳转到登录页
    console.log(parseInt(response.data.code) === 1000)
    if (parseInt(response.data.code) === 1000 || parseInt(response.data.code) === 2000){

        Message({message:response.data.msg,type:'error'});
        router.push({
            path: '/login'
        });
        localStorage.removeItem('userInfo')
        return Promise.reject(res.data.msg);
    }
    return response;
}, function (error) {
    // 对响应错误做点什么
    console.log(error)
    return Promise.reject(error);
});



export default {
    get:function(path='',data={}){
        return new Promise((resolve, reject)=>{
            axios.get(path,{
                params:data
            }).then((response)=>{
                resolve(response)
            }).catch((err)=>{
                reject(err)
            })
        })
    },
    post:function (path='',data={}) {
        return new Promise((resolve, reject) =>{
            axios.post(path,data).then((response)=>{
                resolve(response)
            }).catch((err)=>{
                reject(err)
            })
        } )

    },
    delete: function (path = '', data = {}) {
        return new Promise(function (resolve, reject) {
            axios.delete(path, data)
                .then(function (response) {
                    resolve(response)
                })
                .catch(function (err) {
                    reject(err)
                })
        })
    },


}
